package cn.hdufocus.focus_helper.aspect;

import cn.hdufocus.focus_helper.exception.ForbiddenException;
import cn.hdufocus.focus_helper.util.CaptchaUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Aspect
@Component
public class RequestAspect {

    //使用org.slf4j.Logger,这是spring实现日志的方法
    private final static Logger logger = LoggerFactory.getLogger(RequestAspect.class);

    /**
     * 表示在执行被@MonitorRequest注解修饰的方法之前 会执行doBefore()方法
     *
     * @param joinPoint 连接点，就是被拦截点
     */
    @Before(value = "@annotation(cn.hdufocus.focus_helper.annotation.MonitorRequest)")
    public void doBefore(JoinPoint joinPoint) {
        //获取到请求的属性
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取到请求对象
        HttpServletRequest request = attributes.getRequest();
        String ticket = request.getHeader("ticket");
        String randStr = request.getHeader("randstr");
        String ip = request.getRemoteAddr();
        if("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)){
            //根据网卡取本机配置的IP
            InetAddress inet=null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ip = inet.getHostAddress();
        }
        boolean flag = CaptchaUtil.checkTicket(ticket,randStr,ip);
        if (flag==false){
            throw new ForbiddenException();
        }
    }
}